﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//引用模型类
using Model;

namespace DAL
{
    public class UsersDAL
    {
        //注册
        public bool Add(Users u)
        {
            using (TuCaoWangEntities db=new TuCaoWangEntities())
            {
                db.Users.Add(u);//添加到集合
                db.SaveChanges();//保存到数据库
                return true;
            }
        }
        //登录
        public Users Login(string uname, string pwd)
        {
            using (TuCaoWangEntities db = new TuCaoWangEntities())
            {
                //使用Linq方法语法查询登录用户注册的用户名和密码
                Users login = (Users)db.Users.FirstOrDefault(u => (u.UserName == uname && u.UserPass == pwd));
                return login;
            }
        }

        //查询所有用户
        public List<Users> GetAll()
        {
            using (TuCaoWangEntities db = new TuCaoWangEntities())
            {
                return db.Users.Include("Articles").ToList();
                //return db.Users.ToList<Users>();
            }
        }
        //查询指定用户
        public Users GetUserByID(int? id)
        {
            using (TuCaoWangEntities db = new TuCaoWangEntities())
            {
                return db.Users.Find(id);
            }
        }
        //查询指定用户的帖子
        public List<Articles> GetArticlesByID(int id)
        {
            using (TuCaoWangEntities db = new TuCaoWangEntities())
            {
                return db.Users.Find(id).Articles.ToList(); ;
            }
        }

        //修改密码
        public bool UpdatePwd(Users update)
        {
            try
            {
                using (TuCaoWangEntities db = new TuCaoWangEntities())
                {
                    Users old = db.Users.Find(update.ID);//获取要修改的帖子对象
                    old.UserPass = update.UserPass;//修改对象属性:密码
                    db.SaveChanges();//保存到数据库
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
